﻿
using MixingStation.LTWebService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;

//操作服务器帮助
namespace MixingStation
{
    class ServerCommonHelper
    {
        //判断是否联网
        public static bool IsWebServiceAvaiable(Uri url)
        {
            try
            {
                if (IsPingSuccess(url.Host))
                {
                    using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                    {
                        client.getDateTime();
                    }
                    //HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url.ToString());
                    //using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
                    //{
                    //    return true;
                    //}
                }
                else
                {
                    return false;
                }
            }
            //catch (WebException e)
            //{
            //    if (e.Status == WebExceptionStatus.ProtocolError)
            //    {
            //    }
            //}
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        private static bool IsPingSuccess(string ipAddr)
        {
            try
            {
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(ipAddr, 120);//第一个参数为ip地址，第二个参数为ping的时间 
                if (reply.Status == IPStatus.Success)
                {
                    //ping的通 
                    return true;
                }
                else
                {
                    //ping不通 
                    return false;
                } 
            }
            catch
            {
                return false;
            }
        }

        //获取车辆
        public static carWS GetCar(string carNumber, int carType, long belongCorpId)
        {
            carWS car = new carWS();
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    car = client.getCar(belongCorpId, carNumber);//获取车辆信息
                    if (car != null)
                        return car;
                    else
                        return CreatCar(carNumber, carType, belongCorpId, client);//获取车ID
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (Exception)
                {
                    return CreatCar(carNumber, carType, belongCorpId, client);//获取车ID
                }
            }
        }

        //根据车牌号创建车辆信息
        private static carWS CreatCar(string carNumber, int carType, long belongCorpId, LTCardAPIServiceClient client)
        {
            carWS car = new carWS();
            car.maxWeightSpecified = true;
            car.invalidSpecified = true;
            car.typesSpecified = true;
            //flag：0销售1采购2全部
            if (carType == 0)
                car.flag = 0;
            else if (carType == 1 || carType == 2)
                car.flag = 1;
            corpWS corp = new corpWS();
            corp.id = belongCorpId;//公司id
            corp.idSpecified = true;
            car.belongCorp = corp;
            car.models = "汽车";
            car.code = carNumber;
            car.driver = "";
            car.maxWeight = 0;
            car.invalid = true;
            try
            {
                resultWS res = client.saveCar(car);
                if (res.isSuccessful)
                    return client.getCarById(res.id);
                else
                {
                    LogHelper.error("创建车辆信息失败：" + res.message);
                    throw new Exception("创建车辆信息失败:" + res.message); 
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.error("创建车辆信息异常:" + ex.Message);
                return null;
            }
        }

        //判断车牌号是否在场内
        public static bool IsCarIn(long carId)
        {
            bool isCarInHouse = false;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    isCarInHouse = client.isCarIn(carId);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    LogHelper.error("判断车辆是否在厂内异常：" + ex.ToString());
                    return false;
                }
            }
            return isCarInHouse;
        }

        //创建purchaseCardWS
        public static purchaseCardWS CreatePurchaseCard(carWS car, userWs user, WeightRecordInfo formInfo)
        {
            purchaseCardWS purchaseCard = new purchaseCardWS();
            purchaseCard.cardId = "";
            purchaseCard.cardState = 1;
            purchaseCard.car = car;
            if (formInfo.PurchaseOrder != null)
            {
                purchaseCard.purchaseOrder = formInfo.PurchaseOrder;
                purchaseCard.supplier = formInfo.PurchaseOrder.supplier;
                purchaseCard.material = formInfo.PurchaseOrder.material;
                purchaseCard.place = formInfo.PurchaseOrder.place;
            }
            purchaseCard.userId = Convert.ToInt64(user.id);
            purchaseCard.userIdSpecified = true;
            purchaseCard.employeeId = Convert.ToInt64(user.employeeId);
            purchaseCard.employeeIdSpecified = true;
            purchaseCard.grossWeight = formInfo.TempWeight;
            purchaseCard.grossWeightSpecified = true;
            purchaseCard.firstWeightDate = DateTime.Now;
            purchaseCard.firstWeightDateSpecified = true;
            //第一次称重时默认第二次称重时间为当前时间，查询是过滤出秤时间
            purchaseCard.secondWeightDate = DateTime.Now;
            purchaseCard.secondWeightDateSpecified = true;
            purchaseCard.weighman = user.employeeName;
            purchaseCard.reasons = formInfo.Remark;
            return purchaseCard;
        }

        //将本地数据装WeightRecordInfo
        public static WeightRecordInfo ConvertWeightRecordInfoByRow(DataGridViewRow selectedRow)
        {
            WeightRecordInfo weightRecordInfo = new WeightRecordInfo ();
            try
            {
                if (selectedRow.DataGridView.Columns["SystemIdColumn"] != null)
                    weightRecordInfo.SystemId = Convert.ToInt64(selectedRow.Cells["SystemIdColumn"].Value);
                weightRecordInfo.CarCode = selectedRow.Cells["CarCodeColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["OrderCodeColumn"] != null)
                    weightRecordInfo.OrderCode = selectedRow.Cells["OrderCodeColumn"].Value.ToString();
                weightRecordInfo.MaterialCode = selectedRow.Cells["MaterialCodeColumn"].Value.ToString();
                weightRecordInfo.MaterialName = selectedRow.Cells["MaterialColumn"].Value.ToString();
                weightRecordInfo.SupplierCode = selectedRow.Cells["SupplierCodeColumn"].Value.ToString();
                weightRecordInfo.SupplierName = selectedRow.Cells["SupplierColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["PlaceCodeColumn"] != null)
                    weightRecordInfo.PlaceCode = selectedRow.Cells["PlaceCodeColumn"].Value.ToString();
                weightRecordInfo.PlaceName = selectedRow.Cells["PlaceColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["DirectionCodeColumn"] != null)
                    weightRecordInfo.DirectionCode = selectedRow.Cells["DirectionCodeColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["DirectionColumn"] != null)
                    weightRecordInfo.DirectionName = selectedRow.Cells["DirectionColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["ReceiveCodeColumn"] != null)
                    weightRecordInfo.ReceiveCode = selectedRow.Cells["ReceiveCodeColumn"].Value.ToString();
                if (selectedRow.DataGridView.Columns["ReceiveNameColumn"] != null)
                    weightRecordInfo.ReceiveName = selectedRow.Cells["ReceiveNameColumn"].Value.ToString();

                decimal grossWeight = Convert.ToDecimal(selectedRow.Cells["GrossWeightColumn"].Value);
                weightRecordInfo.GrossWeight = grossWeight;
                weightRecordInfo.FirstWeightTime = Convert.ToDateTime(selectedRow.Cells["FirstWeightTimeColumn"].Value);
                weightRecordInfo.FirstWeightman = selectedRow.Cells["WeightManColumn"].Value.ToString();
                decimal tareWeight = Convert.ToDecimal(selectedRow.Cells["TareWeightColumn"].Value);
                weightRecordInfo.TareWeight = tareWeight;
                weightRecordInfo.LastWeightTime = Convert.ToDateTime(selectedRow.Cells["LastWeightTimeColumn"].Value);
                weightRecordInfo.LastWeightman = selectedRow.Cells["TareWeightManColumn"].Value.ToString();
                decimal buckleWeight = Convert.ToDecimal(selectedRow.Cells["BuckleWeightColumn"].Value);
                weightRecordInfo.BuckleWeight = buckleWeight;
                weightRecordInfo.BuckleReasons = selectedRow.Cells["BuckleReasonsColumn"].Value.ToString();
                weightRecordInfo.NetWeight = grossWeight - tareWeight - buckleWeight;
                if (selectedRow.DataGridView.Columns["IsPurchaseColumn"] != null)
                    weightRecordInfo.IsPurchase = selectedRow.Cells["IsPurchaseColumn"].Value.ToString() == "是" ? true : false;
                if (selectedRow.DataGridView.Columns["IsBackColumn"] != null)
                    weightRecordInfo.IsBack = selectedRow.Cells["IsBackColumn"].Value.ToString() == "是" ? true : false;
                if (selectedRow.DataGridView.Columns["PrintedColumn"] != null)
                    weightRecordInfo.IsPrinted = selectedRow.Cells["PrintedColumn"].Value.ToString() == "已打印" ? true : false;
                if (selectedRow.DataGridView.Columns["StatusColumn"] != null)
                    weightRecordInfo.IsCompleted = selectedRow.Cells["StatusColumn"].Value.ToString() == "完结" ? true : false;
                if (selectedRow.DataGridView.Columns["UploadStatusColumn"] != null)
                    weightRecordInfo.UploadStatus = selectedRow.Cells["UploadStatusColumn"].Value.ToString()
                    == "第一次称重已上传" ? (int)UploadedEnum.FirstUploaded : (selectedRow.Cells["UploadStatusColumn"].Value.ToString() 
                    == "未上传" ? (int)UploadedEnum.UnUploaded : (int)UploadedEnum.Uploaded);
                weightRecordInfo.Remark = selectedRow.Cells["RemarkColumn"].Value.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.error("将表格数据转换WeightRecordInfo异常：" + ex.Message.ToString());
                return null;
            }
            return weightRecordInfo;
        }


        //更新purchaseCardWS
        public static void UpdatePurchaseCard(userWs user, WeightRecordInfo formInfo, ref purchaseCardWS purchaseCard)
        {
            purchaseCard.userId = Convert.ToInt64(user.id);
            purchaseCard.userIdSpecified = true;
            purchaseCard.employeeId = Convert.ToInt64(user.employeeId);
            purchaseCard.employeeIdSpecified = true;
            purchaseCard.tareWeight = formInfo.TareWeight;
            purchaseCard.tareWeightSpecified = true;
            purchaseCard.tareWeightMan = user.employeeName;
            purchaseCard.buckleWeight = formInfo.BuckleWeight;
            purchaseCard.buckleWeightSpecified = true;
            purchaseCard.buckleReasons = formInfo.BuckleReasons;
            if (formInfo.DeliveryWeight > 0)
            {
                purchaseCard.deliveryWeight = formInfo.DeliveryWeight;
                purchaseCard.deliveryWeightSpecified = true;
            }
            if (formInfo.PurchaseOrder != null && !string.IsNullOrEmpty(formInfo.PurchaseOrder.code))
            {
                purchaseCard.purchaseOrder = formInfo.PurchaseOrder;
                purchaseCard.supplier = formInfo.PurchaseOrder.supplier;
                purchaseCard.material = formInfo.PurchaseOrder.material;
                purchaseCard.place = formInfo.PurchaseOrder.place;
            }
            //皮重称完
            purchaseCard.cardState = 3;
            purchaseCard.firstWeightDate = formInfo.FirstWeightTime;
            purchaseCard.firstWeightDateSpecified = true;

            purchaseCard.secondWeightDate = DateTime.Now;
            purchaseCard.secondWeightDateSpecified = true;
            purchaseCard.isBack = formInfo.IsBack;
            purchaseCard.isBackSpecified = true;
            purchaseCard.printed = formInfo.IsPrinted;
            purchaseCard.printedSpecified = true;
            purchaseCard.reasons = formInfo.Remark;
        }


        public static purchaseCardWS CreatePurchaseCardByRecord(userWs user, int belongCorpId, WeightRecordInfo recordInfo)
        {
            purchaseCardWS purchaseCard = new purchaseCardWS();
            purchaseCard.cardId = "";
            purchaseCard.cardState = 4;

            string carCode = recordInfo.CarCode;
            carWS car = GetCar(carCode, 2, belongCorpId);
            if (car == null)
                return null;
            purchaseCard.car = car;
            purchaseCard.purchaseOrder = recordInfo.PurchaseOrder;
            purchaseCard.supplier = recordInfo.PurchaseOrder.supplier;
            purchaseCard.material = recordInfo.PurchaseOrder.material;
            purchaseCard.place = recordInfo.PurchaseOrder.place;
            purchaseCard.userId = Convert.ToInt64(user.id);
            purchaseCard.userIdSpecified = true;
            purchaseCard.employeeId = Convert.ToInt64(user.employeeId);
            purchaseCard.employeeIdSpecified = true;
            purchaseCard.grossWeight = recordInfo.GrossWeight;
            purchaseCard.grossWeightSpecified = true;
            purchaseCard.firstWeightDate = recordInfo.FirstWeightTime;
            purchaseCard.firstWeightDateSpecified = true;
            purchaseCard.weighman = recordInfo.FirstWeightman;
            purchaseCard.tareWeight = recordInfo.TareWeight;
            purchaseCard.tareWeightSpecified = true;
            if (recordInfo.DeliveryWeight > 0)
            {
                purchaseCard.deliveryWeight = recordInfo.DeliveryWeight;
                purchaseCard.deliveryWeightSpecified = true;
            }
            purchaseCard.tareWeightMan = recordInfo.LastWeightman;
            purchaseCard.buckleWeight = recordInfo.BuckleWeight;
            purchaseCard.buckleWeightSpecified = true;
            purchaseCard.buckleReasons = recordInfo.BuckleReasons;
            purchaseCard.secondWeightDate = recordInfo.LastWeightTime;
            purchaseCard.secondWeightDateSpecified = true;
            purchaseCard.reasons = recordInfo.Remark;
            return purchaseCard;
        }

        //获取历史平均数据type = 0,毛重 1：皮重
        public static decimal GetPurCarWeightAverage(int type, long id)
        {
            System.Nullable<decimal>[] carweightArr = null;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    carweightArr = client.getPurCarWeightAverage(id);
                    if (carweightArr != null && carweightArr.Length > 0)
                        return (decimal)carweightArr[type];
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    LogHelper.error("保存purchaseCard异常：" + ex.Message);
                    return -1;
                }
            }
            return -1;
        }

        //保存采购数据
        public static bool SavePurchaseCard(purchaseCardWS purchaseCard)
        {
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    resultWS result = client.savePurchaseCard(purchaseCard);
                    if (!result.isSuccessful)
                    {
                        LogHelper.error("保存purchaseCard失败：" + result.message);
                        return false;
                    }
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch(Exception ex)
                {
                    LogHelper.error("保存purchaseCard异常：" + ex.Message);
                    return false;
                }
            }
            return true;
        }

        //根据车牌号获取purchaseCardWS
        public static purchaseCardWS GetPurchaseCard(string carCode)
        {
            purchaseCardWS purchaseCard = null;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    purchaseCard = client.getPurchaseCard("", carCode, 0);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch
                {
                    return null;
                }
            }
            return purchaseCard;
        }

        //根据Id获取purchaseCardWS
        public static purchaseCardWS GetPurchaseCardByID(long id)
        {
            purchaseCardWS purchaseCard = null;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    purchaseCard = client.getPurchaseCardById(id);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    LogHelper.error("根据ID：" + id + "获取purchaseCardWS异常：" + ex.Message);
                    return null;
                }
            }
            return purchaseCard;
        }

        //修改purchaseCard信息（毛重、皮重以及订单）
        public static bool UploadPurchaseCards(purchaseCardWS[] purchaseCardArr)
        {
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    resultWS result = client.uploadPurchaseCards(purchaseCardArr);
                    if(!result.isSuccessful)
                    {
                        LogHelper.error("修改purchaseCard失败：" + result.message);
                        return false;
                    }
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch(Exception ex)
                {
                    LogHelper.error("修改purchaseCard异常：" + ex.Message);
                    return false;
                }
            }
            return true;
        }

        //获取用户实体
        public static userWs GetUserByName(string userName)
        {
            userWs user = null;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    user = client.getUser(userName);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    LogHelper.error("获取用户" + userName + "异常：" + ex.Message);
                    return null;
                }
            }
            return user;
        }

        //根据车牌号获取purchaseCardWS
        public static purchaseCardWS GetPurchaseCardBefore(long carId)
        {
            purchaseCardWS purchaseCard = null;
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                try
                {
                    purchaseCard = client.getPurchaseCardBefore(carId);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    throw;
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch
                {
                    return null;
                }
            }
            return purchaseCard;
        }

        //非二类物资保存称重保存
        public static long SaveWeightRecords(string user, string password)
        {
            long systemId = -1;
            string strErrMsg = string.Empty;
            try
            {
                int res = ServerCommonHelper.putJsonData("saveWeightRecords", "", ref strErrMsg);
                if (res != -1)//系统异常或者业务数据异常
                {
                    LogHelper.error(strErrMsg);
                    if (res == 2)
                    {
                        if (!ServerCommonHelper.JsonLogin(user, password))
                            return -1;
                        return SaveWeightRecords(user, password);
                    }
                    throw new Exception(strErrMsg == null ? ("type:" + res + ", message:null") : strErrMsg);
                }
                else
                {
                    string jsondata = CGlobal.strSwapJsonData;
                    CGlobal.strSwapJsonData = string.Empty;
                    if (jsondata == "[]")
                        return -1;
                    systemId = long.Parse(jsondata);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("非二类物资保存称重保存异常：" + ex.ToString());
                throw new Exception(ex.Message);
            }
            return systemId;
        }

        //非二类物资查询
        public static List<WeightRecordInfo> GetWeightRecordsByCondition(string user, string password)
        {
            List<WeightRecordInfo> list = new List<WeightRecordInfo>();
            string strErrMsg = string.Empty;
            try
            {
                int res = ServerCommonHelper.putJsonData("findWeightRecordsByCondition", "", ref strErrMsg);
                if (res != -1)//系统异常或者业务数据异常
                {
                    LogHelper.error(strErrMsg);
                    if (res == 2)
                    {
                        if (!ServerCommonHelper.JsonLogin(user, password))
                            return null;
                        return GetWeightRecordsByCondition(user, password);
                    }
                    throw new Exception(strErrMsg == null ? ("type:" + res + ", message:null") : strErrMsg);
                }
                else
                {
                    string jsondata = CGlobal.strSwapJsonData;
                    CGlobal.strSwapJsonData = string.Empty;
                    if (jsondata == "[]")
                        return null;
                    JArray jar = JArray.Parse(jsondata);
                    for (int i = 0; i < jar.Count; i++)
                    {
                        WeightRecordInfo info = new WeightRecordInfo();
                        if (jar[i]["systemId"] != null && !string.IsNullOrEmpty(jar[i]["systemId"].ToString()))
                            info.SystemId = long.Parse(jar[i]["systemId"].ToString());
                        if (jar[i]["carCode"] != null && !string.IsNullOrEmpty(jar[i]["carCode"].ToString()))
                            info.CarCode = jar[i]["carCode"].ToString();
                        if (jar[i]["materialCode"] != null && !string.IsNullOrEmpty(jar[i]["materialCode"].ToString()))
                            info.MaterialCode = jar[i]["materialCode"].ToString();
                        if (jar[i]["materialName"] != null && !string.IsNullOrEmpty(jar[i]["materialName"].ToString()))
                            info.MaterialName = jar[i]["materialName"].ToString();
                        if (jar[i]["supplierCode"] != null && !string.IsNullOrEmpty(jar[i]["supplierCode"].ToString()))
                            info.SupplierCode = jar[i]["supplierCode"].ToString();
                        if (jar[i]["supplierName"] != null && !string.IsNullOrEmpty(jar[i]["supplierName"].ToString()))
                            info.SupplierName = jar[i]["supplierName"].ToString();
                        if (jar[i]["placeCode"] != null && !string.IsNullOrEmpty(jar[i]["placeCode"].ToString()))
                            info.PlaceCode = jar[i]["placeCode"].ToString();
                        if (jar[i]["placeName"] != null && !string.IsNullOrEmpty(jar[i]["placeName"].ToString()))
                            info.PlaceName = jar[i]["placeName"].ToString();
                        if (jar[i]["directionCode"] != null && !string.IsNullOrEmpty(jar[i]["directionCode"].ToString()))
                            info.DirectionCode = jar[i]["directionCode"].ToString();
                        if (jar[i]["directionName"] != null && !string.IsNullOrEmpty(jar[i]["directionName"].ToString()))
                            info.DirectionName = jar[i]["directionName"].ToString();
                        if (jar[i]["receiveCode"] != null && !string.IsNullOrEmpty(jar[i]["receiveCode"].ToString()))
                            info.ReceiveCode = jar[i]["receiveCode"].ToString();
                        if (jar[i]["receive"] != null && !string.IsNullOrEmpty(jar[i]["receive"].ToString()))
                            info.ReceiveName = jar[i]["receive"].ToString();
                        if (jar[i]["tempWeight"] != null && !string.IsNullOrEmpty(jar[i]["tempWeight"].ToString()))
                            info.TempWeight = decimal.Parse(jar[i]["tempWeight"].ToString());
                        if (jar[i]["grossWeight"] != null && !string.IsNullOrEmpty(jar[i]["grossWeight"].ToString()))
                            info.GrossWeight = decimal.Parse(jar[i]["grossWeight"].ToString());
                        if (jar[i]["tareWeight"] != null && !string.IsNullOrEmpty(jar[i]["tareWeight"].ToString()))
                            info.TareWeight = decimal.Parse(jar[i]["tareWeight"].ToString());
                        if (jar[i]["buckleWeight"] != null && !string.IsNullOrEmpty(jar[i]["buckleWeight"].ToString()))
                            info.BuckleWeight = decimal.Parse(jar[i]["buckleWeight"].ToString());
                        if (jar[i]["buckleReasons"] != null && !string.IsNullOrEmpty(jar[i]["buckleReasons"].ToString()))
                            info.BuckleReasons = jar[i]["buckleReasons"].ToString();
                        if (jar[i]["netWeight"] != null && !string.IsNullOrEmpty(jar[i]["netWeight"].ToString()))
                            info.NetWeight = decimal.Parse(jar[i]["netWeight"].ToString());
                        if (jar[i]["firstWeightTime"] != null && !string.IsNullOrEmpty(jar[i]["firstWeightTime"].ToString()))
                            info.FirstWeightTime = Convert.ToDateTime(jar[i]["firstWeightTime"].ToString());
                        if (jar[i]["firstWeightMan"] != null && !string.IsNullOrEmpty(jar[i]["firstWeightMan"].ToString()))
                            info.FirstWeightman = jar[i]["firstWeightMan"].ToString();
                        if (jar[i]["lastWeightTime"] != null && !string.IsNullOrEmpty(jar[i]["lastWeightTime"].ToString()))
                            info.LastWeightTime = Convert.ToDateTime(jar[i]["lastWeightTime"].ToString());
                        if (jar[i]["lastWeightMan"] != null && !string.IsNullOrEmpty(jar[i]["lastWeightMan"].ToString()))
                            info.LastWeightman = jar[i]["lastWeightMan"].ToString();
                        if (jar[i]["remark"] != null && !string.IsNullOrEmpty(jar[i]["remark"].ToString()))
                            info.Remark = jar[i]["remark"].ToString();
                        if (jar[i]["isPrinted"] != null && !string.IsNullOrEmpty(jar[i]["isPrinted"].ToString()))
                            info.IsPrinted = Convert.ToBoolean(jar[i]["isPrinted"].ToString());
                        if (jar[i]["isRecord"] != null && !string.IsNullOrEmpty(jar[i]["isRecord"].ToString()))
                            info.IsRecord = Convert.ToBoolean(jar[i]["isRecord"].ToString());
                        if (jar[i]["isCompleted"] != null && !string.IsNullOrEmpty(jar[i]["isCompleted"].ToString()))
                            info.IsCompleted = Convert.ToBoolean(jar[i]["isCompleted"].ToString());
                        list.Add(info);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("非二类物资查询异常：" + ex.ToString());
                throw new Exception(ex.Message);
            }
            return list;
        }

        //根据车牌号获取最近一次称重记录
        public static WeightRecordInfo GetLastWeightRecordByCarCode(string user, string password)
        {
            WeightRecordInfo info = new WeightRecordInfo();
            string strErrMsg = string.Empty;
            string tempJsondata = "";
            try
            {
                int res = ServerCommonHelper.putJsonData("findLastWeightRecordByCarCode", "", ref strErrMsg);
                if (res != -1)//系统异常或者业务数据异常
                {
                    LogHelper.error(strErrMsg);
                    if (res == 2)
                    {
                        if (!ServerCommonHelper.JsonLogin(user, password))
                            return null;
                        return GetLastWeightRecordByCarCode(user, password);
                    }
                    throw new Exception(strErrMsg == null ? ("type:" + res + ", message:null") : strErrMsg);
                }
                else
                {
                    string jsondata = CGlobal.strSwapJsonData;
                    CGlobal.strSwapJsonData = string.Empty;
                    if (jsondata == "[]" || jsondata == "{}")
                        return null;
                    tempJsondata = jsondata;
                    JObject jobj = JObject.Parse(jsondata);
                    if (jobj["materialCode"] != null && !string.IsNullOrEmpty(jobj["materialCode"].ToString()))
                        info.MaterialCode = jobj["materialCode"].ToString();
                    if (jobj["supplierCode"] != null && !string.IsNullOrEmpty(jobj["supplierCode"].ToString()))
                        info.SupplierCode = jobj["supplierCode"].ToString();
                    if (jobj["placeCode"] != null && !string.IsNullOrEmpty(jobj["placeCode"].ToString()))
                        info.PlaceCode = jobj["placeCode"].ToString();
                    if (jobj["directionCode"] != null && !string.IsNullOrEmpty(jobj["directionCode"].ToString()))
                        info.DirectionCode = jobj["directionCode"].ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("根据车牌号获取最近一次称重记录异常：" + ex.ToString() + "jsonData:" + tempJsondata);
                throw new Exception(ex.Message);
            }
            return info;
        }

        public static bool JsonLogin(string user, string password)
        {
            //JsonUrl地址
            CGlobal.strJsonUrl = ConfigurationManager.AppSettings["JsonUrl"].ToString();
            CGlobal.strCur_user = user;
            CGlobal.strPasswd = password;
            //登录
            LoginCheckData bd = new LoginCheckData();
            bd.username = CGlobal.strCur_user;
            bd.password = CGlobal.strPasswd;
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(bd);
            string strRtnErrorMsg = string.Empty;
            int res = ServerCommonHelper.putJsonData("Login", "", ref strRtnErrorMsg);
            if (res != -1)
            {
                LogHelper.error("Json登录失败：" + strRtnErrorMsg);
                return false;
            }
            return true;
        }

        //发送json数据
        public static int putJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }
            try
            {
                string url = "";
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 180000;
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);
                request.ContentType = "application/json;charset=UTF-8";

                request.Accept = "application/json";
                request.Method = "PUT";
                request.AllowWriteStreamBuffering = true;

                byte[] postBytes = Encoding.UTF8.GetBytes(CGlobal.strSwapJsonData);
                request.ContentLength = postBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Flush();
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                bool exception = true;
                if (response.Headers["Set-Cookie"] != null)
                    CGlobal.cookie = response.Headers.Get("Set-Cookie");
                if (response.Headers["Date"] != null)
                    CGlobal.dtLoginTime = Convert.ToDateTime(response.Headers.Get("Date"));
                if (response.Headers["Exception"] != null)
                    exception = Convert.ToBoolean(response.Headers.Get("Exception"));

                Stream responseStream = response.GetResponseStream();
                string stringResponse = string.Empty;
                //UTF8方式读取上传返回信息字符串
                using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    stringResponse = responseReader.ReadToEnd();
                }

                responseStream.Close();
                response.Close();

                if (exception)
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(stringResponse);
                    strErrorMsg = result.message;
                    return result.type;
                }
                //操作成功
                CGlobal.strSwapJsonData = stringResponse;
                return -1;
             
            }
            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return -3;
            }
        }

        //获取json数据
        public static int getJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            int res = -1;

            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }

            string url = "";
            try
            {
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);

                request.ContentType = "application/json;charset=UTF-8";
                request.Accept = "application/json";
                request.Method = "GET";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                bool exception = true;
                if (response.Headers["Exception"] != null)
                    exception = Convert.ToBoolean(response.Headers.Get("Exception"));

                Stream stream = response.GetResponseStream();
                string jsondata = "";
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        jsondata += reader.ReadLine();
                    }
                }
                stream.Close();
                response.Close();

                if (exception)
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(jsondata);
                    strErrorMsg = result.message;
                    return result.type;
                }
                //操作成功
                CGlobal.strSwapJsonData = jsondata;
                return res;
            }

            catch (WebException)  //webExcp
            {
                strErrorMsg = "服务器请求数据错误，请检查服务器是否运行。" + CGlobal.strJsonUrl;
                return 1;
            }

            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return 1;
            }
        }

        public static string getURL(string WorkFlowType, string flowno)
        {
            string url = "";
            url = CGlobal.strJsonUrl;
            switch (WorkFlowType)
            {
                case "Login":    //
                    url = url + "login";
                    break;
                case "allUser":    //
                    url = url + "allUser";
                    break;
                case "saveWeightRecords":    //保存称重数据
                    url = url + "saveWeightRecords";
                    break;
                case "findWeightRecordsByCondition":    //根据条件查询数据
                    url = url + "findWeightRecordsByCondition";
                    break;
                case "findMaxIdOfWeightRecords":    //获取WeightRecords表中Id最大值
                    url = url + "findMaxIdOfWeightRecords";
                    break;
                case "findLastWeightRecordByCarCode":    //获取最近一次称重记录
                    url = url + "findLastWeightRecordByCarCode";
                    break;
                default: break;
            }
            return url;
        }
    }
}
